﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EasyStep.Data.Entities;
using EasyStep.Attributes;
using EasyStep.TestExecution.Data;
using EasyStep.TestExecution;
using WPF.TestEditor.Properties;
using System.ComponentModel;
using WPF.TestEditor.Controls.History;

namespace WPF.TestEditor.Controls
{
    public partial class TestStepView : UserControlBase
    {
        public List<TestStepResult> Results { get; private set; }
        public Guid Id
        {
            get
            {
                var data = this.DataContext as TestStep;
                return data == null ? Guid.Empty : data.Id;
            }
        }
        public static readonly DependencyProperty TotalResultProperty = DependencyProperty.Register("TotalResult", typeof(ExecutionResult), typeof(TestStepView));
        public ExecutionResult TotalResult
        {
            get { return (ExecutionResult)GetValue(TotalResultProperty); }
            set { SetValue(TotalResultProperty, value); }
        }

        public TestStepView(TestStep data)
        {            
            this.DataContext = data;
            InitializeComponent();
            ClearResults();
            this.Loaded += new RoutedEventHandler(TestStepView_Loaded);
        }

        void TestStepView_Loaded(object sender, RoutedEventArgs e)
        {
            ReinitControls(this.DataContext as TestStep);
        }

        private void ReinitControls(TestStep data)
        {
            this.lblActions.Text = data == null ? "null" : GetActionInfo(data.Action);
            this.lblInfo.Text = data == null ? "null" : data.OrderNr.ToString();
            this.lblData.Text = data == null ? "null" : GetDataInfo(data.Locator, data.Data);
            RefreshStatus();
        }

        private string GetDataInfo(TestData locator, TestData data)
        {
            if (locator == null && data == null) return "null";
            StringBuilder sb = new StringBuilder();
            if (locator != null) sb.Append(locator.Value);
            if (locator != null && data != null) sb.Append("\t\\\t").Append(data.Value);
            else if (data != null) sb.Append(data.Value);
            return sb.ToString();
        }

        private string GetActionInfo(TestAction testAction)
        {
            if (testAction == null) return "null";
            return testAction.Parent != null
                ? string.Format("{0}\\{1}", testAction.Parent.Name, testAction.Name)
                : testAction.Name;
        }

        public void SetResult(TestStepResult result)
        {
            lock (Results)
            {
                var existing = Results.Where(r => r.Browser.Equals(result.Browser, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (existing != null) Results.Remove(existing);
                Results.Add(result);
                ReinitControls(result.StepInfo);
            }
        }
        public void ClearResults()
        {
            Results = new List<TestStepResult>();
            RefreshStatus();
        }
        public void RefreshStatus()
        {
            try
            {
                TotalResult = AnalizeTestBrowserResult(Results);
                var src= new BitmapImage(new Uri(GetImageIndex(TotalResult, false)));                
                this.pnlResultImage.Source = src.Clone();
                this.pnlResultText.Text = TotalResult.ToString();
            }
            catch (Exception ex)
            {
                ProcessException(ex);
            }
        }

        private void ProcessException(Exception ex)
        {
            if (TestDataContext != null)
                TestDataContext.Log.Fatal("Can't Refresh Test Step status!", ex);
            else
                MessageBox.Show("Can't Refresh Test Step status!\r\n" + ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
        }
        private ExecutionResult AnalizeTestBrowserResult(IEnumerable<TestStepResult> results)
        {
            if (results==null || !results.Any())
                return ExecutionResult.NoResult;
            if (results.Where(ri => ri.Result == ExecutionResult.Failed).Any())
                return ExecutionResult.Failed;
            if (results.Where(ri => ri.Result == ExecutionResult.InProgress).Any())
                return ExecutionResult.InProgress;
            return ExecutionResult.Success;
        }

        private string GetImageIndex(ExecutionResult result, bool forSelectedNode = false)
        {
            return GetNodeImage(result.ToString() + "16.png", forSelectedNode);
        }
        private string GetNodeImage(string key, bool selected = false)
        {
            return System.IO.Path.Combine(Settings.Default.ResourceFolder, key);
        }
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        #endregion
        private void MouseLeftButton_Down(object sender, MouseButtonEventArgs e)
        {

            IsExpanded = !IsExpanded;
            

        }



        public bool IsExpanded
        {
            get
            {
                return pnlMoreInfo.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                if (pnlMoreInfo.Visibility != System.Windows.Visibility.Visible)
                {
                    pnlMoreInfo.Children.Clear();
                    foreach (var item in Results)
                    {
                        var stpResult = new StepResult(item);
                        pnlMoreInfo.Children.Add(stpResult);
                    }
                    pnlMoreInfo.Visibility = System.Windows.Visibility.Visible;
                }
                else
                    pnlMoreInfo.Visibility = System.Windows.Visibility.Collapsed;

            }
        }
    }



}
